package com.hue.concurrent.day01;

/*
    两阶段终止模式：优雅的停止一个线程
        Thread.currentThread().isInterrupted():获取打断标记，不会清除打断标记
        Thread.interrupted():获取打断标记，但是会清除打断标记
        Thread.currentThread().interrupt():设置打断标记
 */
public class Demo11 {
    public static void main(String[] args) {
        TwoStop twoStop = new TwoStop();
        twoStop.start();

        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        twoStop.stop();
    }

    public static class TwoStop{
        private Thread monitor;

        //开启一个线程
        public void start(){
            monitor = new Thread(()->{
                while (true){
                    if(Thread.currentThread().isInterrupted()){
                        System.out.println("monitor线程被打断，处理后事");
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                        System.out.println("正常监控");
                    } catch (InterruptedException e) {
                        System.out.println("monitor睡眠中被打断");
                        //当前线程处理sleep状态被打断后标记为false，手动将标记置为true
                        Thread.currentThread().interrupt();
                    }
                }
            });
            monitor.start();
        }

        //停止monitor线程
        public void stop(){
            monitor.interrupt();
        }
    }
}

